package com.example.hzit.controller.admin;

import com.example.hzit.entity.User;
import com.example.hzit.service.UserService;
import com.example.hzit.utils.JwtUtil;
import com.example.hzit.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class AdminLoginController {

    @Autowired
    private UserService userService;

    // 用户登录
    @PostMapping("/login")
    public R login(@RequestBody User user) {
        if (userService.authenticate(user.getUsername(), user.getPassword())) {
            String token = JwtUtil.generateToken(user.getUsername());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return R.ok().data(map);
        } else {
            return R.error().message("用户名或密码错误");
        }
    }

    // 获取用户信息
    @GetMapping("/info")
    public R info(@RequestParam("token") String token) {
        String username = JwtUtil.getUsernameFromToken(token);
        if (username != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", username);
            map.put("avatar", "https://example.com/default-avatar.png");
            return R.ok().data(map);
        } else {
            return R.error().message("无效的token");
        }
    }

    // 用户注册
    @PostMapping("/signin")
    public R userSignin(@RequestBody User user) {
        if (userService.register(user)) {
            return R.ok().message("注册成功");
        } else {
            return R.error().message("注册失败");
        }
    }
}
